#include "button_stm32.h"
#include "gpio.h"
#include "iSwitch.h"

#define debugPrint(str, ...) 

Button::Button():callback(NULL)
{
    /*-------------------初始按键并配置功能-------------------*/
    // 初始化按键 设置触发为低电平，消抖时间为2tick(20ms)
    iSW_Init(hisw, this->ButtonNum, iSW_TRIGGER_LEVEL_LOW, 2);
    // 设置按键0为模式2，长按时间为200tick(2s)，短按时间为2tick(20ms)
    // 触发方式为按下触发，双击时间为4~15tick(40ms~150ms)
    iSW_Set_Mode2(&hisw[0], 200, 2, iSW_TRIGGER_WAY_PRESS);
    iSW_Set_Double_Click(&hisw[0], 4, 15);
    // 设置按键1为模式2，长按时间为200tick(2s)，短按时间为2tick(20ms) 触发方式为按下触发
    // 触发方式为按下触发，双击时间为4~15tick(40ms~150ms)
    iSW_Set_Mode2(&hisw[1], 200, 2, iSW_TRIGGER_WAY_PRESS);
    iSW_Set_Double_Click(&hisw[1], 4, 15);
}

void Button::SetLongPressTime(uint8_t id, uint32_t _longPressTime)
{
    if (id < this->ButtonNum)
    {
        iSW_Set_Mode2(&hisw[id], _longPressTime, 20, iSW_TRIGGER_WAY_PRESS);
    }
}

void Button::SetOnEventListener(void (*_callback)(uint8_t id, uint8_t events))
{
    callback = _callback;
}

bool Button::ReadButtonPinIO(uint8_t _id)
{
    switch (_id)
    {
        case 1:
            return HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin) == GPIO_PIN_SET;
        case 2:
            return HAL_GPIO_ReadPin(KEY2_GPIO_Port, KEY2_Pin) == GPIO_PIN_SET;
        default:
            return false;
    }
}

bool Button::IsPressed(uint8_t id)
{
    return !ReadButtonPinIO(id);
}

void Button::Tick10ms(void)
{
    uint8_t input[2] = {ReadButtonPinIO(1), ReadButtonPinIO(2)};
    if (iSW_Scan(hisw, input, this->ButtonNum))
    {
        if (callback != NULL)
        {
            if (hisw[0].events)
            {
                callback(1, hisw[0].events);
            }
            if (hisw[1].events)
            {
                callback(2, hisw[1].events);
            }
        }
        iSW_Clear(hisw, this->ButtonNum);
    }
}

